package com.shun.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

/**
 * Spring Context 工具类使用
 * 
 * @author clever
 * @since 2021-09-27
 */
@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware, DisposableBean {

	private static ApplicationContext applicationContext = null;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtil.applicationContext = applicationContext;
	}

	@Override
	public void destroy() throws Exception {
        applicationContext = null;
	}
	
	/**
	 * 获得bean名字获得Bean
	 * @param <T>
	 * @param beanName
	 * @return
	 */
	public static <T> T getBean(String beanName) {
		return (T) applicationContext.getBean(beanName);
	}

	/**
	 * 根据bean的类获得Bean
	 * @param <T>
	 * @param clzType
	 * @return
	 */
	public static <T> T getBean(Class<T> clzType) {
		return applicationContext.getBean(clzType);
	}
	
	/**
	 * 发布事件
	 * 
	 * @param event
	 */
	public static void publishEvent(ApplicationEvent event) {
		if (event != null) {
			applicationContext.publishEvent(event);
		} else {
			log.warn("applicationContext为空！");
		}
	}

	/**
	 * 获取当前环境
	 * @return
	 */
	public static String getActiveProfile() {
		return applicationContext.getEnvironment().getActiveProfiles()[0];
	}
}
